package model;

import java.util.ArrayList;

import com.fmn.dots_final_i_hope.PlayerControl;

import android.app.Activity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

public class GameField {

	public static void createField(Activity activity, ImageView[][] gameField) {
		for (int i = 0; i < gameField.length; i++) {
			for (int j = 0; j < gameField[i].length; j++) {
				String drawObjectID = "drawObject_" + i + "_" + j;
				int resID = activity.getResources().getIdentifier(drawObjectID, "id",
						activity.getPackageName());
				gameField[i][j] = ((ImageView) activity.findViewById(resID));
			}
		}
	}

	public static ArrayList<Square> extractSquares(ImageView[][] field) {
		ArrayList<Square> m = new ArrayList<Square>();
		for (int row = 0; row < field.length; row++) {
			for (int col = 0; col < field[row].length; col++) {

				if (field[row][col] instanceof Square
						&& !((Square) field[row][col]).getAlreadyObtained())
					m.add((Square) field[row][col]);
			}
		}
		return m;
	}

	
	public static void setReferences(ImageView[][] field) {

		for (int row = 0; row < field.length; row++) {
			for (int col = 0; col < field[row].length; col++) {

				if (row % 2 == 0) {
					if (col % 2 != 0) {

						try {
							((Line) field[row][col])
									.setSurroundingSquare1((Square) field[row - 1][col]);
						} catch (ArrayIndexOutOfBoundsException e) {
							// e.printStackTrace();
						}

						try {
							((Line) field[row][col])
									.setSurroundingSquare2((Square) field[row + 1][col]);
						} catch (ArrayIndexOutOfBoundsException e) {
							// e.printStackTrace();
						}
					}
				} else {
					if (col % 2 == 0) {
						((Line) field[row][col]).setVertical();
						try {
							((Line) field[row][col])
									.setSurroundingSquare1((Square) field[row][col + 1]);
						} catch (ArrayIndexOutOfBoundsException e) {
							// e.printStackTrace();
						}

						try {
							((Line) field[row][col])
									.setSurroundingSquare2((Square) field[row][col - 1]);
						} catch (ArrayIndexOutOfBoundsException e) {
							// e.printStackTrace();
						}

					} else {

						// here no catch-block is needed because we are sure we
						// have square surrounding objects

						((Square) field[row][col])
								.setSurroundingLineReferences(
										(Line) field[row][col - 1],
										(Line) field[row][col + 1],
										(Line) field[row - 1][col],
										(Line) field[row + 1][col]);
					}
				}
			}
		}
	}
	
	
	public static void setLineListeners(ImageView[][] gameField,
			View.OnTouchListener listener) {
		for (int i = 0; i < gameField.length; i++) {
			for (int j = 0; j < gameField[i].length; j++) {

				if ((i % 2 == 0 && j % 2 != 0) || (i % 2 != 0 && j % 2 == 0)) {
					gameField[i][j].setOnTouchListener(listener);
				}
			}
		}
	}
	
}
